package com.example.administrator.printoutindemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;


import com.example.administrator.printoutindemo.services.Tools;
import com.example.administrator.printoutindemo.services.dyjApplication;

import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class StoreListMonthked extends Activity {

	private ListView store_listView_monthsked = null;

	private Mothsked mothsked = null;
	private List<Mothsked> li_mo = null;
	private StoreListMonthkedAdapter adapter = null;

	private Bitmap bitmap = null;

	private Mothsked selectmo = null;
	private int mstatus = 0;

	private static final String WEBSERVICE_CONFIG = "webServiceInfo";
	private static final int LOGINSUCCESS = 0;
	private static final int NETWORKERROR = 2;
	private static final int SYSERROR = 3;
	private static final int UPSUCCESS = 4;
	private static final int UPEROOR = 5;

	ProgressDialog progressDiaog;

	private final Handler hanlder = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
				case LOGINSUCCESS:

					bindList();

					progressDiaog.dismiss();
					break;
				case UPSUCCESS:
					bindList();
					Toast.makeText(StoreListMonthked.this, "上传成功!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case UPEROOR:
					bindList();

					Toast.makeText(StoreListMonthked.this, "上传失败!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case NETWORKERROR:

					Toast.makeText(StoreListMonthked.this, "网络或系统异常!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case SYSERROR:

					Toast.makeText(StoreListMonthked.this, "系统异常!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;

				default:
					progressDiaog.dismiss();
					break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_activity_listmonthked);

		store_listView_monthsked = (ListView) findViewById(R.id.store_listView_monthsked);

		mothsked = new Mothsked();
		adapter = new StoreListMonthkedAdapter(this);

		final int user_id = ((dyjApplication) getApplication()).get_user_id();

		if (user_id != 0) {

			progressDiaog = new ProgressDialog(StoreListMonthked.this);
			progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
			progressDiaog.setTitle("提示");
			// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
			progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
			progressDiaog.setIndeterminate(false);// 设置进度条不明确
			progressDiaog.setCancelable(true);

			progressDiaog.show();
			new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						li_mo = callWebServiceGetInfo(String.valueOf(user_id));

						if (li_mo != null) {
							Message m = new Message();
							m.what = StoreListMonthked.LOGINSUCCESS;
							hanlder.sendMessage(m);
						}

					} catch (Exception e) {
						Message m = new Message();
						m.what = StoreListMonthked.SYSERROR;
						hanlder.sendMessage(m);
					}

				}
			}).start();
		} else {
			Tools.showDialogInfo(this, "登录已过期，请重新登录");
		}

	}

	private void bindList() {

		List<Mothsked> li = new ArrayList<Mothsked>();

		for (Mothsked m : li_mo) {
			if (m.getMstatus() == 2 || m.getMstatus() == 3) {
				li.add(m);
			}
		}

		adapter.setList(li);
		store_listView_monthsked.setAdapter(adapter);
		// 点击
		store_listView_monthsked
				.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
											int position, long id) {

						view.setBackgroundResource(R.color.danqing);

						selectmo = li_mo.get(position);
						mstatus = li_mo.get(position).getMstatus();

						Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 调用相机

						startActivityForResult(in, 1);//

						// Intent intent = new Intent(StoreListMonthked.this,
						// StoreListMonthked.class);
						//
						// Bundle mBundle = new Bundle();
						//
						// mBundle.putSerializable("Mothsked",
						// li_mo.get(position));
						// intent.putExtras(mBundle);
						//
						// startActivity(intent);
					}
				});

	}

	// 返回照相机图片处理
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {

			Bundle bundle = data.getExtras();
			bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

			if (null != bitmap) {
				progressDiaog = new ProgressDialog(StoreListMonthked.this);
				progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
				progressDiaog.setTitle("提示");
				// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
				progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
				progressDiaog.setIndeterminate(false);// 设置进度条不明确
				progressDiaog.setCancelable(true);

				progressDiaog.show();

				try {

					sendPhoto(bitmap);

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}

		}
	}

	/**
	 * 发送图片消息
	 */
	private void sendPhoto(final Bitmap bitmap) {

		new Thread(new Runnable() {

			@Override
			public void run() {

				ByteArrayOutputStream os = new ByteArrayOutputStream();

				/**
				 * Bitmap.CompressFormat.JPEG 和 Bitmap.CompressFormat.PNG JPEG 与
				 * PNG 的是区别在于 JPEG是有损数据图像，PNG使用从LZ77派生的无损数据压缩算法。 这里建议使用PNG格式保存
				 * 100 表示的是质量为100%。当然，也可以改变成你所需要的百分比质量。 os 是定义的字节输出流
				 *
				 * .compress() 方法是将Bitmap压缩成指定格式和质量的输出流
				 */
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);

				byte[] photo = os.toByteArray();

				SimpleDateFormat df = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");// 设置日期格式
				String JSdate = df.format(new Date());// new Date()为获取当前系统时间


				if (mstatus == 2) {
					selectmo.setCyimg(photo);
					selectmo.setMstatus(3);
				}
				if (mstatus == 3) {
					selectmo.setFqimg(photo);
					selectmo.setMstatus(4);
					selectmo.setJSdate(JSdate);
				}

				List<Mothsked> li_upService = new ArrayList<Mothsked>();

				li_upService.add(selectmo);

				// 上传服务器
				if (uploadInfo(li_upService)) {
					Message m = new Message();
					m.what = StoreListMonthked.UPSUCCESS;
					hanlder.sendMessage(m);
				}
				else {
					Message m = new Message();
					m.what = StoreListMonthked.UPEROOR;
					hanlder.sendMessage(m);
				}

			}
		}).start();

	}

	// 上传数据至服务器
	private boolean uploadInfo(List<Mothsked> li) {

		boolean bl = false;

		for (int i = 0; i < li.size(); i++) {
			Mothsked n = li.get(i);
			String jsonStr = mothsked.ConvertToJson(n);

			try {

				/****************** 调用webService ***********************/
				// 调用.net 的WebService.
				String nameSpace = "http://dyjapp.org/";
				String methodName = "";
				if (mstatus == 2) {
					methodName = "UpdateCyimg";
				}
				if (mstatus == 3) {
					methodName = "UpdateFqimg";
				}



				SharedPreferences sPreferencces = getSharedPreferences(
						WEBSERVICE_CONFIG, 0);

				String url = "http://" + sPreferencces.getString("ip", "")
						+ ":" + sPreferencces.getString("Port", "")
						+ "/StoreService.asmx";// "http://192.168.1.101/webservice/default.asmx";
				// // 10.0.2.2
				// 为Android模拟器的本地(localhost)IP
				String soapAction = nameSpace + methodName;

				// 设置连接参数
				SoapObject request = new SoapObject(nameSpace, methodName);

				// 增加属性参数。 将相关的函数参数放入到过程中。
				request.addProperty("modelJson", jsonStr);

				if (mstatus == 2) {
					byte[] ps = n.getCyimg();
					String photo = new String(Base64.encode(ps)); // 进行Base64编码

					request.addProperty("cyimg", photo);
				}
				if (mstatus == 3) {
					byte[] ps = n.getFqimg();
					String photo = new String(Base64.encode(ps)); // 进行Base64编码

					request.addProperty("fqimg", photo);
				}



				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
				// V1.1）;

				// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
				// 不指定rpc方式则用true否则要用false
				envelope.dotNet = true;

				// envelope.setOutputSoapObject(request);//设置请求参数
				envelope.bodyOut = request; // enveloper.bodyOut=request 与
				// envelope.setOutputSoapObject(request)
				// 效果相同。
				// step4 创建HttpTransportSE对象
				HttpTransportSE ht = new HttpTransportSE(url);
				// step5 调用WebService
				ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
				if (envelope.getResponse() != null) {
					SoapPrimitive response = (SoapPrimitive) envelope
							.getResponse();
					if (!("0".equals(response.toString()))) {
						bl = true;
					}

				}
				/****************** 调用webService结束 ***********************/

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		return bl;
	}

	private List<Mothsked> callWebServiceGetInfo(String user_id) {

		List<Mothsked> result = null;

		try {

			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "GetVmonthsked";
			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";

			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("user_id", user_id);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
				// if ("1".equals(response.toString())) {
				String t = response.toString();

				if (!t.equals("")) {
					result = mothsked.getListFromJSON(t);
				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			// TODO: handle exception
			progressDiaog.dismiss();
		}

		return result;
	}

}